<template>
  <div class="admin-messages">
    <!-- 搜索和筛选区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="消息标题">
          <el-input v-model="filterForm.title" placeholder="请输入消息标题" clearable />
        </el-form-item>
        <el-form-item label="消息类型">
          <el-select v-model="filterForm.type" placeholder="请选择消息类型" clearable>
            <el-option
              v-for="item in messageTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleCreate">新增消息</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 消息表格 -->
    <el-table
      :data="messageList"
      border
      style="width: 100%"
      v-loading="loading"
      @sort-change="handleSortChange"
    >
      <el-table-column prop="id" label="ID" width="80" sortable="custom" />
      <el-table-column prop="title" label="标题" min-width="150" />
      <el-table-column prop="type" label="类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getTypeTagType(row.type)">
            {{ getTypeText(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" sortable="custom" />
      <el-table-column prop="updateTime" label="更新时间" width="180" sortable="custom" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 消息编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="50%"
    >
      <el-form :model="messageForm" label-width="100px">
        <el-form-item label="消息标题" prop="title">
          <el-input v-model="messageForm.title" placeholder="请输入消息标题" />
        </el-form-item>
        <el-form-item label="消息类型" prop="type">
          <el-select v-model="messageForm.type" placeholder="请选择消息类型">
            <el-option
              v-for="item in messageTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="消息内容" prop="content">
          <el-input
            v-model="messageForm.content"
            type="textarea"
            :rows="5"
            placeholder="请输入消息内容"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="messageForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 消息类型选项
const messageTypes = [
  { value: 1, label: '系统通知' },
  { value: 2, label: '活动公告' },
  { value: 3, label: '站内消息' },
  { value: 4, label: '版本更新' }
]

// 状态选项
const statusOptions = [
  { value: 1, label: '已发布' },
  { value: 0, label: '未发布' }
]

// 筛选表单
const filterForm = reactive({
  title: '',
  type: '',
  status: ''
})

// 排序字段
const sortField = reactive({
  prop: '',
  order: ''
})

// 表格数据
const messageList = ref([])
const loading = ref(false)

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEditMode = ref(false)
const messageForm = reactive({
  id: '',
  title: '',
  type: 1,
  content: '',
  status: 1
})

// 获取消息列表
const fetchMessages = async () => {
  try {
    loading.value = true
    // 这里替换为实际的API调用
    // const params = {
    //   ...filterForm,
    //   page: pagination.currentPage,
    //   size: pagination.pageSize,
    //   sortField: sortField.prop,
    //   sortOrder: sortField.order
    // }
    // const res = await getMessages(params)
    // messageList.value = res.data.list
    // pagination.total = res.data.total
    
    // 模拟数据
    messageList.value = [
      {
        id: 1,
        title: '系统维护通知',
        type: 1,
        content: '系统将于今晚进行维护升级',
        status: 1,
        createTime: '2023-05-10 14:00:00',
        updateTime: '2023-05-10 14:00:00'
      },
      {
        id: 2,
        title: '端午节活动公告',
        type: 2,
        content: '端午节期间将举办优惠活动',
        status: 0,
        createTime: '2023-05-20 10:00:00',
        updateTime: '2023-05-20 10:00:00'
      }
    ]
    pagination.total = 15
  } catch (error) {
    ElMessage.error('获取消息列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchMessages()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = ''
  })
  sortField.prop = ''
  sortField.order = ''
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchMessages()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchMessages()
}

// 排序变化
const handleSortChange = ({ prop, order }) => {
  sortField.prop = prop
  sortField.order = order === 'ascending' ? 'asc' : 'desc'
  fetchMessages()
}

// 获取类型标签样式
const getTypeTagType = (type) => {
  const map = {
    1: '',         // 系统通知
    2: 'success',  // 活动公告
    3: 'info',     // 站内消息
    4: 'warning'   // 版本更新
  }
  return map[type] || ''
}

// 获取类型文本
const getTypeText = (type) => {
  const option = messageTypes.find(item => item.value === type)
  return option ? option.label : '未知类型'
}

// 状态变更
const handleStatusChange = async (row) => {
  try {
    // 调用API更新状态
    // await updateMessageStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    // 失败后恢复原状态
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

// 新增消息
const handleCreate = () => {
  dialogTitle.value = '新增消息'
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑消息
const handleEdit = (row) => {
  dialogTitle.value = '编辑消息'
  isEditMode.value = true
  Object.assign(messageForm, row)
  dialogVisible.value = true
}

// 删除消息
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这条消息吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用API删除
      // await deleteMessage(row.id)
      ElMessage.success('删除成功')
      fetchMessages()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 重置表单
const resetForm = () => {
  Object.assign(messageForm, {
    id: '',
    title: '',
    type: 1,
    content: '',
    status: 1
  })
}

// 提交表单
const submitForm = async () => {
  try {
    if (isEditMode.value) {
      // 调用API更新
      // await updateMessage(messageForm)
      ElMessage.success('更新成功')
    } else {
      // 调用API新增
      // await createMessage(messageForm)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    fetchMessages()
  } catch (error) {
    ElMessage.error(isEditMode.value ? '更新失败' : '添加失败')
  }
}

// 初始化加载
onMounted(() => {
  fetchMessages()
})
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>